/**
 * @description 弹出框常用操作
 * @since 2019-03-06
 * @author Rid King
*/

import Vue from 'vue'
import DialogerComp from '../../components/dialoger/dialoger.vue'

// 弹出框类
class Dialoger {
  /**
   * @function 构造方法
   * @param options {Object} // 配置对象
  */
  constructor (options) {
    // 添加组件容器
    let mountEl = document.createElement('div')
    let id = String('dialoger_' + Math.random()).replace('.', '')
    mountEl.id = id
    document.body.appendChild(mountEl)

    // 挂载组件
    let DiaComp = Vue.extend(DialogerComp)
    this._dia = new DiaComp({
      propsData: options
    }).$mount('#' + id)
  }

  /**
   * @function 显示
  */
  show () {
    this._dia.show()
  }

  /**
   * @function 隐藏
  */
  hide () {
    // 隐藏后销毁
    this.hide()
    setTimeout(() => {
      this._dia.remove()
    }, 100)
  }
}

export default {
  /**
   * @function 弹出提示信息
   * @param options {Object} // 配置对象
   * @return {Promise}
  */
  alert (options) {
    return this.dialog(this.mergeOptions(options, {
      hasCancel: false
    }))
  },

  /**
   * @function 弹出提示信息
   * @param options {Object} // 配置对象
   * @return {Promise}
  */
  confirm (options) {
    return this.dialog(this.mergeOptions(options, {
      hasCancel: true,
      width: '250px'
    }))
  },

  /**
   * @function 弹出提示信息
   * @param options {Object} // 配置对象
   * @return {Promise}
  */
  success (options) {
    return this.dialog(this.mergeOptions(options, {
      hasCancel: false
    }))
  },

  /**
   * @function 弹出提示信息
   * @param options {Object} // 配置对象
   * @return {Promise}
  */
  warning (options) {
    return this.dialog(this.mergeOptions(options, {
      hasCancel: false
    }))
  },

  /**
   * @function 弹出提示信息
   * @param options {Object} // 配置对象
   * @return {Promise}
  */
  error (options) {
    return this.dialog(this.mergeOptions(options, {
      hasCancel: false
    }))
  },

  /**
   * @function 弹出框
   * @param options {Object} // 配置对象
   * @return {Promise}
  */
  dialog (options) {
    return new Promise((resolve, reject) => {
      let opts = this.mergeOptions(options, {
        onSure () {
          resolve(true)
          return true
        },
        oncancel () {
          resolve(false)
          return false
        }
      })
      let dia = new Dialoger(opts)
      dia.show()
    })
  },

  /**
   * @function 获取合并配置
   * @param options {Object} // 指定配置
   * @return {Object}
  */
  mergeOptions (options, merged) {
    if (!(typeof options === 'object' && options !== null)) {
      options = {}
    }
    return Object.assign(options, merged)
  }
}
